package com.glela.controller;


import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.glela.common.util.HttpUtil;
import com.glela.common.util.SmsContents;

public class SendSMS {
	private static Logger logger = LoggerFactory.getLogger(SendSMS.class);
	
//	public static String send(String postData, String postUrl) {
//		try {
//			//发送POST请求
//			URL url = new URL(postUrl);
//            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//            conn.setRequestMethod("POST");
//            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//            conn.setRequestProperty("Connection", "Keep-Alive");
//            conn.setUseCaches(false);
//            conn.setDoOutput(true);
//
//            conn.setRequestProperty("Content-Length", "" + postData.length());
//            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
//            out.write(postData);
//            out.flush();
//            out.close();
//
//            //获取响应状态
//            if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
//                System.out.println("connect failed!");
//                return "";
//            }
//            //获取响应内容体
//            String line, result = "";
//            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
//            while ((line = in.readLine()) != null) {
//                result += line + "\n";
//            }
//            System.out.println(result);
//            in.close();
//            return result;
//        } catch (IOException e) {
//            e.printStackTrace(System.out);
//        }
//        return "";
//	}
	 
	public static String send(String postData, String postUrl) {
		try {
			return sendSms(postData);
        } catch (Exception e) {
            e.printStackTrace(System.out);
        }
        return "";
	}
	
	 
	public static void main(String args[]) throws UnsupportedEncodingException{
		sendSms("userid=&account=98a33e&password=kn2t9xmhpz&mobile=18017978790&content=您的会员（小鸟）申请售后服务，订单号：4365465464564565，申请时间：20170530 。【校妆网】");
		sendSms("mobile=18017978790&content=您的验证码是4543【校妆网】");
		sendSms("mobile=18017978790&content=您正在找回登录密码，验证码为56564（切勿告知他人），30分钟内有效。如有问题请及时联系客服400-036-9090【校妆网】");
	} 
	//该方法后面修改为 消息队列异步实现, 减少当前TOMCAT应用服务器HTTP请求阻塞。
	//本方法是为了应对只发一个类上线而临时写的
	public static String sendSms(String context)  {
		try {
			String rgex = "mobile=(.*?)&"; 
	        String m = getSubUtilSimple(context, rgex);
	        String rgex2 = "content=(.*)";
	        String cont = getSubUtilSimple(context, rgex2);
	        System.out.println(m + "-------------"  + cont);
	        if(StringUtils.isBlank(m)) {
	        	logger.error("短信发送失败: 无法解析字符串: " , context);
	        	return null;
	        }
	        if(StringUtils.isBlank(cont)) {
	        	logger.error("短信发送失败: 无法解析字符串: " , context);
	        	return null;
	        }
			SmsContents contents = new  SmsContents(m, cont);
			String code = HttpUtil.doPost(contents.toString(), "http://www.jianzhou.sh.cn/JianzhouSMSWSServer/http/sendBatchMessage", "application/x-www-form-urlencoded");
			
			System.out.println("短信发送返回值: " + code);
			return code;
			
		}catch(Exception e) {
			logger.error("短信发送失败:" , e.getMessage(), e);
		}
		
		return null;
	}
	
    /** 
     * 正则表达式匹配两个指定字符串中间的内容 
     * @param soap 
     * @return 
     */  
    public static List<String> getSubUtil(String soap,String rgex){  
        List<String> list = new ArrayList<String>();  
        Pattern pattern = Pattern.compile(rgex);// 匹配的模式  
        Matcher m = pattern.matcher(soap);  
        while (m.find()) {  
            int i = 1;  
            list.add(m.group(i));  
            i++;  
        }  
        return list;  
    }  
      
    /** 
     * 返回单个字符串，若匹配到多个的话就返回第一个，方法与getSubUtil一样 
     * @param soap 
     * @param rgex 
     * @return 
     */  
    public static String getSubUtilSimple(String soap,String rgex){
        Pattern pattern = Pattern.compile(rgex);// 匹配的模式  
        Matcher m = pattern.matcher(soap);  
        while(m.find()){  
            return m.group(1);  
        }  
        return "";  
    } 
    
    
	
	
	
}
